<?php

class orderModel extends RPHP_Model
{

    protected $_auth  = null;
    protected $appid  = 10002;
    protected $appkey = 'd0488e0c8963fd6aaecfdf96a092b65c';

    //检查权限
    public function checkPriv($pv, $return = true, $menu = true)
    {
        $auth = $this->auth->CheckPriv($pv, $return, $menu);
        if ($return) {
            $this->_auth = $auth;
        }

        return $auth;
    }

    //获取所有快递列表
    public function getExpressCompany()
    {
        $sql = "SELECT * FROM {$this->_prefix['primary']}express_company WHERE `stat`=1  ORDER BY `sort` DESC,`id` ASC";
        return $this->sql($sql);
    }

    //查询单个商品状态
    public function getORderOne($data)
    {
        $sql = "SELECT `return_goods_status`,`refund_status` FROM {$this->_prefix['primary']}order_goods WHERE `rec_id`=" . $data;
        return $this->db->getrow($sql);
    }

    //选择地址
    public function saveAddrInfo($da)
    {
       $id = intval($da['id']);
       if($id){
           $data = $this->getRegionAjax($id);

       }


       return $data;
    }

    //申请退货
    public function getReturnEdit($data)
    {
        $code = 900;
        //开始事务
        $this->db->begin();
        $rollback = true;
        if ($data['rec_id']) {
            $rec_id = $data['rec_id'];
        }
        if ($data['order_id']) {
            $order_id = $data['order_id'];
        }
        if ($data['return_goods_status']) {
            $return_goods_status = $data['return_goods_status'];
        }
        if ($return_goods_status == 2 || $return_goods_status == 4) {

            $sql = "UPDATE {$this->_prefix['primary']}order_goods SET `return_goods_status`=" . $return_goods_status . " WHERE `rec_id`=" . $rec_id;
            $row = $this->sql($sql);
            if ($row) {
                $msg = "通过";
                if ($return_goods_status == 4) {
                    $msg = "已收货";
                }

                $code = 200;
                $this->db->commit();
                $rollback = false;

            } else {
                $code = 404;
            }

        }
        if ($return_goods_status == 7) {
            $sql  = "UPDATE {$this->_prefix['primary']}order_goods SET `return_goods_status`=" . $return_goods_status . " ,`shipping_status`=1 WHERE `rec_id`=" . $rec_id;
            $rows = $this->sql($sql);
            if ($rows) {
                $sql  = "SELECT * from {$this->_prefix['primary']}order_info WHERE `order_id`=" . $order_id;
                $info = $this->db->getrow($sql);
                $sql  = "SELECT COUNT(`rec_id`) AS `cnt` FROM {$this->_prefix['primary']}order_goods WHERE `order_id`=" . $order_id . " AND   `return_goods_status` NOT IN (0,7)";
                $cnt  = $this->db->getone($sql);

                $sql = "SELECT COUNT(`rec_id`) AS `cn` FROM {$this->_prefix['primary']}order_goods WHERE `order_id`=" . $order_id . " AND   `shipping_status`=0 ";
                $cn  = $this->db->getone($sql);

                if ($cnt > 0) {
                    $shipping_status = 4; //部分退货
                } else if ($cn > 0) {
                    $shipping_status = 3; //部分已发货
                } else {
                    $shipping_status = 1; //已发货
                }

                if ($info['shipping_status'] != $shipping_status) {
                    $sql = "UPDATE {$this->_prefix['primary']}order_info SET `shipping_status`=" . $shipping_status . " WHERE `order_id`=" . $order_id;
                    $rod = $this->sql($sql);
                    if ($rod) {
                        $msg  = "驳回";
                        $code = 200;
                        $this->db->commit();
                        $rollback = false;

                    } else {
                        $code = 404;
                    }
                } else {
                    $msg  = "驳回";
                    $code = 200;
                    $this->db->commit();
                    $rollback = false;
                }
            }
        }

        if ($rollback) {
            $this->db->rollback();
        }

        $data['code'] = $code;
        $data['msg']  = $msg;
        return $data;

    }

    //申请退款
    public function getReimburseEdit($data)
    {
        $code = 900;
        //开始事务
        $this->db->begin();
        $rollback = true;
        if ($data['rec_id']) {
            $rec_id = $data['rec_id'];
        }
        if ($data['order_id']) {
            $order_id = $data['order_id'];
        }
        if ($data['refund_status']) {
            $refund_status = $data['refund_status'];
        }
        // print_r($refund_status);die;
        if ($refund_status == 2) {

            $sql = "UPDATE {$this->_prefix['primary']}order_goods SET `refund_status`=" . $refund_status . " WHERE `rec_id`=" . $rec_id;
            $row = $this->sql($sql);
            if ($row) {

                $msg  = "通过";
                $code = 200;
                $this->db->commit();
                $rollback = false;

            } else {
                $code = 404;
            }

        }
        if ($refund_status == 5) {

            $sql  = "UPDATE {$this->_prefix['primary']}order_goods SET `refund_status`=" . $refund_status . " WHERE `rec_id`=" . $rec_id;
            $rows = $this->sql($sql);

            if ($rows) {

                $sql  = "SELECT * from {$this->_prefix['primary']}order_info WHERE order_id=" . $order_id;
                $info = $this->db->getrow($sql);

                $sql = "SELECT COUNT(`rec_id`) AS `cnt` FROM {$this->_prefix['primary']}order_goods WHERE `order_id`=" . $order_id . " AND refund_status NOT IN (0,5)";
                $cnt = $this->db->getone($sql);

                //print_r($cnt);die('ddd');
                if ($cnt > 0) {
                    $pay_status = 5; //部分退款

                } else {
                    $pay_status = 2; //已付款
                }
                if ($info['pay_status'] != $pay_status) {

                    $sql = "UPDATE {$this->_prefix['primary']}order_info SET `pay_status`=" . $pay_status . " WHERE `order_id`=" . $order_id;
                    //echo $sql;die;
                    $rod = $this->sql($sql);
                    if ($rod) {
                        $msg  = "驳回";
                        $code = 200;
                        $this->db->commit();
                        $rollback = false;

                    } else {
                        $code = 404;
                    }
                } else {
                    $msg  = "驳回";
                    $code = 200;
                    $this->db->commit();
                    $rollback = false;
                }
            }
        }

        if ($rollback) {
            $this->db->rollback();
        }

        $data['code'] = $code;
        $data['msg']  = $msg;
        return $data;

    }

    //get document
    public function getDocs($docid)
    {
        if (is_array($docid)) {
            $where = " WHERE `docid` IN (" . implode(",", array_unique($docid)) . ")";
        } else {
            $where = " WHERE `docid`=" . intval($docid);
        }

        $sql = "SELECT `docid`,`filename`,`create_time` FROM {$this->_prefix['primary']}documents " . $where;
        $rs  = $this->sql($sql);
        if ($rs) {
            foreach ($rs as $r) {
                $doc[$r['docid']] = $this->c['doc_host'] . date("Ymd", $r['create_time']) . "/" . date("H", $r['create_time']) . "/" . date("i", $r['create_time']) . "/" . $r['filename'];

            }
            return $doc;
        } else {
            return false;
        }

    }
    //获取快递信息列表
    public function getExpressList($para, $page = 1, $pagesize = 20)
    {
        $where = "1=1";
        if ($para['keyword'] != '') {
            $where .= "AND `title` LIKE '%" . $para['keyword'] . "%'";
        }

        $sql = "SELECT COUNT(*) AS `cnt` FROM {$this->_prefix['primary']}express_company  WHERE " . $where;
        $cnt = $this->db->getone($sql);
        if ($cnt > 0) {

            $start = ($page - 1) * $pagesize;
            //默认排序
            $orderby = "`sort` DESC, `id` ASC";

            $sql = "SELECT * FROM {$this->_prefix['primary']}express_company WHERE " . $where . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;
            $rs  = $this->sql($sql);

            return array(
                'page'    => $page,
                'maxpage' => ceil($cnt / $pagesize),
                'count'   => $cnt,
                'data'    => $rs,
                'para'    => $para,

            );
        }

    }

    //添加/编辑 快递
    public function saveExpress($da, $id = 0)
    {

        $code = 900;

        $savegoods               = true; //执行保存的标记
        $field['company_name']   = addslashes(htmlspecialchars(trim($da['company_name'])));
        $field['company_mobile'] = addslashes(htmlspecialchars(trim($da['company_mobile'])));
        $field['company_url']    = addslashes(htmlspecialchars(trim($da['company_url'])));
        //保存信息
        if ($field['company_name'] != "" && $savegoods) {

            $code = 403;

            //开始事务
            $this->db->begin();
            $rollback = true;

            //修改
            if ($id > 0) {
                $field['stat'] = intval($da['stat']);

                //其他必须字段

                $msg = "修改快递失败";

                //修改
                $sql = "UPDATE {$this->_prefix['primary']}express_company SET ";
                foreach ($field as $key => $value) {
                    $upsql[] = "`" . $key . "`='" . $value . "'";
                }
                $sql .= implode(",", $upsql) . " WHERE `id`=" . $id;

                $rcnum = $this->sql($sql);

                if ($rcnum) {

                    $msg  = "修改快递成功";
                    $code = 200;
                    $this->db->commit();
                    $rollback = false;

                } else {
                    $code = 404;
                }

            }
            //新增
            else {
                $msg = "添加快递失败";
                //其他必须字段
                $field['create_time'] = $_SERVER['REQUEST_TIME'];

                foreach ($field as $key => $value) {
                    $keys[]   = "`" . $key . "`";
                    $values[] = "'" . $value . "'";
                }

                //插入
                $sql  = "INSERT INTO {$this->_prefix['primary']}express_company (" . implode(",", $keys) . ") VALUES (" . implode(",", $values) . ")";
                $exID = $this->sql($sql);

                if ($exID > 0) {
                    $code = 200;
                    $msg  = "添加广告成功";
                    $this->db->commit();
                    $rollback = false;

                }

            } //end of add

            if ($rollback) {
                $this->db->rollback();
            }

        }
        $data['code'] = $code;
        $data['msg']  = $msg;
        return $data;
    }
    public function getExpress($id)
    {
        $sql  = "SELECT * FROM {$this->_prefix['primary']}express_company WHERE `id`=" . $id;
        $data = $this->db->getrow($sql);
        return $data;
    }
    // 获取供应商信息
    public function getSupplier($supplier_id = 0)
    {
        if ($supplier_id > 0) {
            $tsql = " AND `id`=" . intval($supplier_id);
        }

        $sql = "SELECT * FROM {$this->_prefix['primary']}supplier WHERE `statu` =1 " . $tsql . " ORDER BY `id` DESC";
        if ($supplier_id > 0) {
            $newdata = $this->db->getrow($sql);
        } else {
            $data = $this->sql($sql);
            if ($data) {
                foreach ($data as $r) {
                    $newdata[$r['supplier_id']] = $r;
                }
            }
        }

        return $newdata;
    }
    //获取供应商发货信息
    public function getSuppliers($supplierid = 0)
    {
        if ($supplierid > 0) {$tsql = " AND `id` = " . $supplierid;}
        $sql = "SELECT * FROM {$this->_prefix['primary']}supplier WHERE `statu` =1 " . $tsql . " ORDER BY `id` DESC";
        if ($supplierid > 0) {
            $data = $this->db->getrow($sql);
        } else {
            $data = $this->sql($sql);
        }

        return $data;
    }
    // 获取客户端打印使用的订单
    public function getClientOrder($da)
    {

        $where = "`pay_status`=2 AND `shipping_status`=0 AND `pay_time`>0 AND `print_stat`=0";

        if ($da['order_id'] != "") {
            $order_id = intval($da['order_id']);
            if ($order_id > 0) {
                $where = "`order_id`=" . $order_id . " AND `pay_status`=2 AND `pay_time`>0";
            }

        }

        $sql   = "SELECT * FROM {$this->_prefix['primary']}order_info WHERE " . $where . " ORDER BY `order_id` ASC LIMIT 1";
        $order = $this->db->getrow($sql);
        if ($order) {
            // 区域信息
            if ($order['province_id'] > 0) {
                $region_id[] = $order['province_id'];
            }

            if ($order['city_id'] > 0) {
                $region_id[] = $order['city_id'];
            }

            if ($order['county_id'] > 0) {
                $region_id[] = $order['county_id'];
            }

            if ($region_id) {
                $sql         = "SELECT `region_id`,`region_name` FROM {$this->_prefix['primary']}region WHERE `region_id` IN (" . implode(",", $region_id) . ")";
                $region_data = $this->sql($sql);
                if ($region_data) {
                    foreach ($region_data as $r) {
                        $region[$r['region_id']] = $r['region_name'];
                    }
                    if ($region) {
                        ksort($region);
                        $region_str = '';
                        foreach ($region as $r) {
                            $region_str .= $r;
                        }
                        $order['address'] = $region_str . $order['address'];
                    }
                }
            }
            // 获取下属商品
            $sql   = "SELECT `goods_id`,`goods_name`,`goods_sn`,`goods_number`,`goods_price`,`original_shop_price` FROM {$this->_prefix['primary']}order_goods WHERE `order_id`=" . $order['order_id'] . " ORDER BY `rec_id` ASC";
            $goods = $this->sql($sql);
            if ($goods) {
                foreach ($goods as $k => $r) {
                    $goods[$k]['goods_amount'] = number_format($r['goods_price'] * $r['goods_number'], 2, ".", "");
                }
                $order['goodscount'] = count($goods);
                $order['goods']      = $goods;
            }

            // 创建时间和付款时间格式化
            $order['pay_time'] = date("Y-m-d H:i:s", $order['pay_time']);
            $order['add_time'] = date("Y-m-d H:i:s", $order['add_time']);
            $order['shipping'] = strip_tags($this->c['para']['shipping_name'][$order['shipping_id']]);

            // 更新为已经打印
            $sql = "UPDATE {$this->_prefix['primary']}order_info SET `print_stat`=1,`print_time`=" . $_SERVER['REQUEST_TIME'] . ",`print_ip`='" . $_SERVER['REMOTE_ADDR'] . "' WHERE `order_id`=" . $order['order_id'];
            $rcs = $this->sql($sql);
            if ($rcs > 0) {
                return $order;
            }

        }
    }

    // 获取指定时间范围，指定快递公司的订单快递信息
    public function getExpressData($da)
    {
        $start_time  = strtotime($da['export_start_date']);
        $end_time    = strtotime($da['export_end_date']);
        $shipping_id = intval($da['shipping_id']);

        if ($start_time > 0 && $end_time > 0 && $start_time < $end_time && $this->c['para']['shipping_name'][$shipping_id]) {
            $sql = "SELECT `uid`,`order_id`,`order_amount`,`pay_fee`,`consignee`,`mobile`,`address`,`province_id`,`city_id`,`county_id`,`pay_time` FROM {$this->_prefix['primary']}order_info WHERE `pay_status`=2 AND `shipping_status`=0 AND `pay_time`>=" . $start_time . " AND `pay_time`<=" . $end_time . " AND `shipping_id`=" . $shipping_id . " ORDER BY `order_id` ASC";

            $data = $this->sql($sql);
            if ($data) {
                foreach ($data as $r) {
                    if ($r['province_id'] > 0) {
                        $region_id[] = $r['province_id'];
                    }

                    if ($r['city_id'] > 0) {
                        $region_id[] = $r['city_id'];
                    }

                    if ($r['county_id'] > 0) {
                        $region_id[] = $r['county_id'];
                    }

                    $uid[] = $r['uid'];
                }
                //

                // 获取用户信息
                $sql       = "SELECT `uid`,`member_gradeid`,`parent_uid` FROM {$this->_prefix['primary']}member_wechat WHERE `uid` IN (" . implode(",", array_unique($uid)) . ")";
                $user_data = $this->sql($sql);
                if ($user_data) {
                    foreach ($user_data as $r) {
                        $user[$r['uid']] = $r;
                        if ($r['member_gradeid'] < 5) {
                            $uids[] = $r['uid'];
                        } elseif ($r['parent_uid'] > 0) {
                            $uids[] = $r['parent_uid'];
                        }

                    }

                    if ($uids) {
                        $sql          = "SELECT `uid`,`realname`,`mobile`,`province_id`,`city_id`,`county_id`,`address` FROM {$this->_prefix['primary']}member_profile WHERE `uid` IN (" . implode(",", array_unique($uids)) . ")";
                        $profile_data = $this->sql($sql);
                        if ($profile_data) {
                            foreach ($profile_data as $r) {
                                if ($r['province_id'] > 0) {
                                    $region_id[] = $r['province_id'];
                                }

                                if ($r['city_id'] > 0) {
                                    $region_id[] = $r['city_id'];
                                }

                                if ($r['county_id'] > 0) {
                                    $region_id[] = $r['county_id'];
                                }

                                $profile[$r['uid']] = $r;
                            }
                        }
                    }
                }

                // 获取区域
                if ($region_id) {
                    $sql         = "SELECT `region_id`,`region_name` FROM {$this->_prefix['primary']}region WHERE `region_id` IN (" . implode(",", $region_id) . ")";
                    $region_data = $this->sql($sql);
                    if ($region_data) {
                        foreach ($region_data as $r) {
                            $region[$r['region_id']] = $r['region_name'];
                        }
                    }
                }

                return array(
                    'data'    => $data,
                    'region'  => $region,
                    'user'    => $user,
                    'profile' => $profile,

                );
            }

        }
    }
    //发货
    public function saveShippingStatus($da)
    {
        $code = 403;
        $msg  = "发货失败，请重试";
        $this->db->begin();

        $rollback      = true;
        $shipping_name = addslashes(htmlspecialchars(trim($da['shipping_name'])));
        $shipping_id   = addslashes(htmlspecialchars(trim($da['shipping_id'])));
        $rec_id        = intval($da['rec_id']);
        $order_id      = intval($da['order_id']);
        if ($shipping_name && $shipping_id && $rec_id && $order_id) {
            $sql  = "SELECT * from {$this->_prefix['primary']}order_info WHERE order_id=" . $order_id;
            $info = $this->db->getrow($sql);
            if ($info['pay_status'] != 0 && $info['order_status'] == 1) {

                // 创建查询单号

                $timestamp = $_SERVER['REQUEST_TIME'];
                $st        = md5($this->appid . $shipping_id . $shipping_name . $timestamp . $this->appkey);
                $url       = "http://api.leatien.com/express/create?appid=" . $this->appid . "&shipping_name=" . $shipping_name . "&shipping_id=" . $shipping_id . "&timestamp=" . $timestamp . "&st=" . $st;

                $tmpjson = @file_get_contents($url);
                if ($tmpjson != "") {
                    $json = json_decode($tmpjson, true);
                    if ($json['code'] == 200) {

                        $sql = "UPDATE {$this->_prefix['primary']}order_goods SET `shipping_id`='" . $shipping_id . "',`shipping_name`='" . $shipping_name . "',`shipping_time`=" . $_SERVER['REQUEST_TIME'] . ",`shipping_status`=1 WHERE `rec_id`=" . $rec_id;
                        $rcs = $this->sql($sql);
                        if ($rcs > 0) {

                            $sql = "SELECT COUNT(`rec_id`) AS `cnt` FROM {$this->_prefix['primary']}order_goods WHERE order_id=" . $order_id . " AND shipping_status = 0";
                            $cnt = $this->db->getone($sql);

                            if ($cnt > 0) {

                                $shipping_status = 3;

                            } else {

                                $shipping_status = 1;
                            }
                            if ($info['shipping_status'] != $shipping_status) {

                                $sql   = "UPDATE {$this->_prefix['primary']}order_info SET `shipping_status`=" . $shipping_status . " WHERE `order_id`=" . $order_id;
                                $re_id = $this->sql($sql);

                                if ($re_id) {
                                    $code   = 200;
                                    $msg    = "发货成功";
                                    $commit = true;

                                }

                            } else {
                                $code   = 200;
                                $msg    = "发货成功";
                                $commit = true;

                            }

                        }
                    } else {
                        $code = $json['code'];
                    }
                }

            }
        } else {
            $code = 900;
            $msg  = "参数缺失，请重试";

        }
        if ($commit) {
            $this->db->commit();

        } else {
            $this->db->rollback();
        }

        $arr             = array();
        $arr['code']     = $code;
        $arr['msg']      = $msg;
        $arr['order_id'] = $order_id;

        return $arr;
    }

    //保存订单状态
    public function saveOrderStatus($order_id, $act, $da = false)
    {
        $code = 404;
        $data = $this->getSingleOrder($order_id);
        //print_r($data);die;
        if ($data) {

            //开始事务
            $this->db->begin();
            $rollback = false;
            $code     = 403;

            switch ($act) {
                case "unpay":
                    $tsql = ",`pay_status`=0";

                    $log_status = '未付款';
                    $log_note   = '设为了未付款状态';

                    break;
                case "payed":
                    $tsql = ",`pay_status`=2,`pay_time`=" . $_SERVER['REQUEST_TIME'] . ",`order_status`=1";

                    $log_status = '已付款';
                    $log_note   = '设为了已付款状态';

                    break;
                case "shipping":
                    $shipping_id   = addslashes(trim($da['shipping_id']));
                    $shipping_name = addslashes(htmlspecialchars(trim($da['shipping_name'])));
                    $tsql          = ",`shipping_time`=" . $_SERVER['REQUEST_TIME'] . ",`shipping_status`=1,`shipping_id`='" . $shipping_id . "',`shipping_name`='" . $shipping_name . "'";
                    $log_status    = '已发货';
                    $log_note      = '设为了已发货<br>' . $shipping_name . ' 单号 ' . $shipping_id;

                    break;
                case "received":
                    $tsql = ",`shipping_status`=2,`receive_time`=" . $_SERVER['REQUEST_TIME'];

                    $log_status = '已收货';
                    $log_note   = '设为了已收货';

                    break;
                case "done":
                    $tsql = ",`pay_status`=2,`order_status`=7,`shipping_status`=9";

                    $log_status = '交易完成';
                    $log_note   = '设为了交易完成';

                    break;
                case "cancel":
                    $tsql       = ",`order_status`=2";
                    $log_status = '取消订单';
                    $log_note   = '设为了取消订单';
                    break;
                case "refund":
                    $tsql       = ",`pay_status`=4,`order_status`=2,`shipping_status`=0";
                    $log_status = '完成退款';
                    $log_note   = '设为了完成退款';

                    $gdsql = "UPDATE {$this->_prefix['primary']}order_goods SET `refund_status`=3 WHERE `refund_status`=1 AND `order_id`=" . $data['order_id'];
                    $rollback = $this->sql($gdsql);

                    if($data['discount_fee']>0 && $rollback){

                        $rollback =  $this->table('discount_coupon')->updateBySql("`status`=0,`used_time`=0,`order_id`=0","`order_id`=".$data['order_id']." AND `status`=1 and `uid`=".$data['uid']);
                    }
                    $f['note'] = "订单 ".$data['order_sn']."退款操作";
                    $f['event'] = 7;
                    $f['dataid'] = $data['order_id'];
                    $f['table_name'] = "order_info";
                    if($data['coupon_fee']>0 && $rollback){

                        $rollback  = $this->finance_change($data['coupon_fee'],$f,$data['uid'],"+","coupon");
                    }


                    if($data['gold_fee']>0 && $rollback){

                        $rollback =  $this->finance_change($data['gold_fee'],$f,$data['uid'],"+","gold_money");
                    }

                    if(!$rollback){
                        return $code;

                    }

                    //$this->table('')

                    break;
                case "refund_turn":
                    $tsql       = ",`pay_status`=2,`order_status`=1,`shipping_status`=0";
                    $log_status = '完成退款驳回';
                    $log_note   = '设为了退款驳回';

                    $gdsql = "UPDATE {$this->_prefix['primary']}order_goods SET `refund_status`=5 WHERE `refund_status`=1 AND `order_id`=" . $data['order_id'];
                    $rollback = $this->sql($gdsql);

                    if(!$rollback){
                        return $code;

                    }

                    break;
                case "rcvgoods":
                    $tsql       = ",`pay_status`=4,`order_status`=2,`shipping_status`=8";
                    $log_status = '完成退款退货';
                    $log_note   = '设为了完成退款与退货';
                    break;
            }

            $sql = "UPDATE {$this->_prefix['primary']}order_info SET `last_staffid`=" . $this->_auth['aid'] . ",`last_staffedit`=" . $_SERVER['REQUEST_TIME'] . $tsql . " WHERE `order_id`=" . $data['order_id'];
            $rc  = $this->sql($sql);
            if ($rc > 0 ) {

                //插入日志
                if ($_POST['comment'] != "") {
                    $log_note .= '<br>备注: ' . addslashes(trim($_POST['comment']));
                }
                $sql = "INSERT INTO {$this->_prefix['primary']}order_log (`order_id`,`staffid`,`status`,`note`,`create_time`) VALUES (" . $data['order_id'] . "," . $this->_auth['aid'] . ",'" . $log_status . "','" . $log_note . "'," . $_SERVER['REQUEST_TIME'] . ")";

                $logid = $this->sql($sql);
                if ($logid > 0) {

                    $rollback = true;

                }
            }

            if (!$rollback) {
                $this->db->rollback();
            }else{

                $this->db->commit();
                $code = 200;
            }

        }
        return $code;
    }



    //资金明细变动
    public function finance_change($money=0,$data=[],$uid=0,$inc="+",$field="money")
    {
        $balance = $this->getBalance($uid);
        if ($balance && $money) {

            $set = $field . "=" . $field . $inc . $money;
            // 更新资金表
            $sql = "UPDATE {$this->_prefix['primary']}finance_balance SET " . $set . " WHERE `uid`=" . $balance['uid'];
            $rcs = $this->sql($sql);
            if ($rcs > 0) {

                $f['note'] = $data['note'];
                $f['event'] = $data['event'];
                $f['uid'] = $balance['uid'];
                $f['cmoney'] = $money;
                $f['money'] = number_format(($balance[$field] + $money), 2, ".", "");
                $f['dataid'] = $data['dataid'] ?? 0;
                $f['table_name'] = $data['table_name'] ?? '';
                $f['create_time'] = $_SERVER['REQUEST_TIME'];

                return $this->table('finance_detail')->insert($f);
            }
        }
        return false;
    }
    //获取快递信息
    public function getShippingInfo($rec_id)
    {
        $sql  = "SELECT * FROM {$this->_prefix['primary']}order_goods WHERE `rec_id`=" . intval($rec_id);
        $data = $this->db->getrow($sql);
        return $data;
    }

    //批量设置发货中

    public function saveOrderShippingStatus($da)
    {
        $data         = array();
        $data['code'] = 900;
        $data['msg']  = "设置失败！";
        if (!empty($da['order_ids'])) {
            $order_ids = trim($da['order_ids']);
            $orders    = explode(',', $order_ids);

            if (!empty($orders)) {
                foreach ($orders as $v) {

                    $sql = "UPDATE {$this->_prefix['primary']}order_info SET `shipping_status`= 5 WHERE `order_id`=" . $v . " AND order_status=1 AND shipping_status=0 AND pay_status=2";
                    $rcs = $this->sql($sql);
                }
                $data['code'] = 200;
                $data['msg']  = "设置成功！";
            }

        } else {

            $data['code'] = 901;
            $data['msg']  = "订单ID不存在";
        }
        return $data;
    }
    //获取单个订单
    public function getSingleOrder($order_id)
    {
        $sql  = "SELECT * FROM {$this->_prefix['primary']}order_info WHERE `order_id`=" . intval($order_id);
        $data = $this->db->getrow($sql);
        if ($data) {
            //获取下属商品
            $data['goods'] = $this->sql("SELECT * FROM {$this->_prefix['primary']}order_goods WHERE `order_id`=" . $data['order_id'] . " ORDER BY `rec_id` ASC");
            foreach ($data['goods'] as &$val) {

                $val['goods_barcode'] = '';
                $val['supplier']      = '';
                $goods_info           = $this->db->getrow("SELECT * FROM {$this->_prefix['primary']}goods_data WHERE `goods_id`=" . $val['goods_id']);

                if (!empty($goods_info['goods_barcode'])) {
                    $val['goods_barcode'] = $goods_info['goods_barcode'];
                }
                /* if ($val['supplierid']) {
                $supplier_info   = $this->db->getrow("SELECT * FROM {$this->_prefix['primary']}supplier WHERE `id`=" . $val['supplierid']);
                $val['supplier'] = $supplier_info['supplier'];
                } */
                if (!empty($goods_info['thumb_docid'])) {
                    $thumb_docid        = $this->getDocs($goods_info['thumb_docid']);
                    $val['thumb_docid'] = $thumb_docid[$goods_info['thumb_docid']];
                } else {
                    $pic_docid        = $this->getDocs($goods_info['pic_docid']);
                    $val['pic_docid'] = $pic_docid[$goods_info['pic_docid']];
                }

                if ($val['stock_id']) {
                    $val['attr_str'] = $this->table('goods_affi_spec')->findOneBySql('`stock_id`='.$val['stock_id'],'spec_name');
                }else{
                    $val['attr_str'] = '';
                }

            }

            //检查门店
            if ($data['storeid'] > 0) {
                $data['store'] = $this->db->getrow("SELECT `storeid`,`name` FROM {$this->_prefix['primary']}shop_store WHERE `storeid`=" . $data['storeid']);
            }

            // 区域信息
            if ($data['province_id'] > 0) {
                $region_id[] = $data['province_id'];
            }

            if ($data['city_id'] > 0) {
                $region_id[] = $data['city_id'];
            }

            if ($data['county_id'] > 0) {
                $region_id[] = $data['county_id'];
            }

            if ($region_id) {
                $sql         = "SELECT `region_id`,`region_name` FROM {$this->_prefix['primary']}region WHERE `region_id` IN (" . implode(",", $region_id) . ")";
                $region_data = $this->sql($sql);
                if ($region_data) {
                    foreach ($region_data as $r) {
                        $region[$r['region_id']] = $r['region_name'];
                    }

                    $data['region'] = $region;
                }
            }
            if ($data['transaction_id'] > 0) {
                $sql                        = "SELECT `transaction_id` FROM {$this->_prefix['primary']}pay_order WHERE `pay_order_id`=" . $data['transaction_id'];
                $data['pay_transaction_id'] = $this->db->getone($sql);
            }

            return $data;
        } else {
            return false;
        }

    }

    //获取订单打印详情
    public function getOrderDetail($order_id)
    {
        $sql  = "SELECT * FROM {$this->_prefix['primary']}order_info WHERE `order_id`=" . intval($order_id);
        $data = $this->db->getrow($sql);
        if ($data) {
            $goods_total = 0;
            //获取下属商品
            $data['goods'] = $this->sql("SELECT * FROM {$this->_prefix['primary']}order_goods WHERE `order_id`=" . $data['order_id'] . " ORDER BY `rec_id` ASC");
            foreach ($data['goods'] as $key => $val) {

                $val['goods_barcode'] = '';
                $val['supplier']      = '';
                $goods_info           = $this->db->getrow("SELECT `goods_sku`,`goods_unit` FROM {$this->_prefix['primary']}goods_data WHERE `goods_id`=" . $val['goods_id']);

                if (!empty($goods_info['goods_sku'])) {
                    $data['goods'][$key]['goods_sku'] = $goods_info['goods_sku'];
                }
                if (!empty($goods_info['goods_unit'])) {
                    $data['goods'][$key]['goods_unit'] = $goods_info['goods_unit'];
                }

                $goods_total += $val['goods_price'];

            }

            // 区域信息
            if ($data['province_id'] > 0) {
                $region_id[] = $data['province_id'];
            }

            if ($data['city_id'] > 0) {
                $region_id[] = $data['city_id'];
            }

            if ($data['county_id'] > 0) {
                $region_id[] = $data['county_id'];
            }

            if ($region_id) {
                $sql         = "SELECT `region_id`,`region_name` FROM {$this->_prefix['primary']}region WHERE `region_id` IN (" . implode(",", $region_id) . ")";
                $region_data = $this->sql($sql);
                if ($region_data) {
                    foreach ($region_data as $r) {
                        $region[$r['region_id']] = $r['region_name'];
                    }

                    $data['region'] = $region;
                }
            }
            $data['goods_total'] = $goods_total;

            return $data;
        } else {
            return false;
        }

    }
    //获取订单操作日志
    public function getOrderLog($order_id)
    {
        $sql  = "SELECT * FROM {$this->_prefix['primary']}order_log WHERE `order_id`=" . intval($order_id) . " ORDER BY `create_time` DESC";
        $data = $this->sql($sql);
        if ($data) {
            foreach ($data as $r) {
                if ($r['staffid'] > 0) {
                    $sid[] = $r['staffid'];
                }

            }
            if ($sid) {
                $staff = $this->getStaff($sid);
            }

            $staff[-99] = '<san class="label label-success">系统</span>';
            return array('data' => $data, 'staff' => $staff);
        } else {
            return false;
        }

    }

    //获取员工信息
    public function getStaff($sid)
    {

        if (is_array($sid)) {
            $tsql = "`aid` IN (" . implode(",", array_unique($sid)) . ")";
        } else {
            $tsql = "`aid`=" . intval($sid);
        }

        $sql  = "SELECT `aid`,`realname` FROM {$this->_prefix['primary']}admin_account WHERE " . $tsql;
        $data = $this->sql($sql);

        if ($data) {
            foreach ($data as $r) {
                $staff[$r['aid']] = $r['realname'];
            }
            return $staff;
        } else {
            return false;
        }

    }

    //获取多个订单
    public function getOrderData($order_ids = "", $start_time = 0, $end_time = 0)
    {
        if ($order_ids != "") {
            $order_id = implode(",", $order_ids);
            $sql      = "SELECT * FROM {$this->_prefix['primary']}order_info WHERE `order_id` in($order_id) ";
            $data     = $this->sql($sql);
            if ($data) {
                //获取下属商品
                foreach ($data as $k => $v) {
                    $data[$k]['goods'] = $this->sql("SELECT * FROM {$this->_prefix['primary']}order_goods WHERE `order_id`=" . $v['order_id'] . " ORDER BY `rec_id` ASC");
                }
                return $data;
            } else {
                return false;
            }

        } else {
            $where = " AND 1=1";

            if ($start_time > 0) {
                $where .= " AND `add_time` >= " . $start_time;
            }
            if ($end_time > 0) {
                $where .= " AND `add_time` <= " . $end_time;
            }
            $sql = "SELECT * FROM {$this->_prefix['primary']}order_info WHERE  1=1" . $where;

            $data = $this->sql($sql);
            if ($data) {
                //获取下属商品
                foreach ($data as $k => $v) {
                    $data[$k]['goods'] = $this->sql("SELECT * FROM {$this->_prefix['primary']}order_goods WHERE `order_id`=" . $v['order_id'] . " ORDER BY `rec_id` ASC");
                }
                return $data;
            } else {
                return false;
            }

        }
    }
    //获取未发货的订单信息
    public function getOrderDatas($start_time = 0, $end_time = 0, $supplier_id = 0, $type = 0)
    {

        if ($type == 1) {

            $where = " AND ord.`order_status`=1 AND ord.`pay_status`>0 AND ord.`shipping_status` NOT IN (0,3)";

        } else {
            $where = " AND ord.`order_status`=1 AND ord.`pay_status`>0 AND ord.`shipping_status` IN (0,3)  AND ogd.`shipping_status`=0 AND ogd.`return_goods_status` IN (0,7) AND ogd.`refund_status` IN (0,5) AND ogd.`shipping_time`=0 ";

        }

        if ($start_time > 0) {
            $where .= " AND ord.`add_time` >= " . $start_time;
        }
        if ($end_time > 0) {
            $where .= " AND ord.`add_time` <= " . $end_time;
        }
        if ($supplier_id > 0) {

            $where .= " AND ogd.`supplierid`=" . $supplier_id;
        }

        // 会员类型
/*        if ($member_type > 0) {

            if ($member_type == 1) {
                $sql = "SELECT `uid` FROM {$this->_prefix['primary']}member_account WHERE `level_type`=1 AND `member_level`>0";
            } elseif ($member_type == 2) {
                $sql = "SELECT `uid` FROM {$this->_prefix['primary']}member_account WHERE `level_type`=2 AND `agent_level`>0";
            } else {
                $sql = "SELECT `uid` FROM {$this->_prefix['primary']}member_account WHERE `level_type`=1 AND `member_level`=0";
            }

            $tmp = $this->sql($sql);
            if ($tmp) {
                foreach ($tmp as $r) {
                    $tmpuids[] = $r['uid'];
                }

                $where .= " AND ord.`uid` IN (" . implode(",", $tmpuids) . ")";
            }
        }*/

        $sql = "SELECT ord.*,ogd.* FROM {$this->_prefix['primary']}order_info ord INNER JOIN {$this->_prefix['primary']}order_goods ogd ON ogd.`order_id` = ord.`order_id` " . $where . " ORDER BY ogd.`rec_id` ASC,ogd.`order_id` ASC";

        $data = $this->sql($sql);
        if ($data) {
            foreach ($data as $r) {
                if ($r['uid'] > 0) {
                    $uids[$r['uid']] = $r['uid'];
                }

                if($r['supplierid']>0){

                    $supplierids[$r['supplierid']] = $r['supplierid'];
                }
            }

            if ($uids) {
                $sql = "SELECT `uid`,`realname`,`name`,`recode` FROM {$this->_prefix['primary']}member_account WHERE `uid` IN (" . implode(",", $uids) . ")";
                $tmp = $this->sql($sql);
                if ($tmp) {
                    foreach ($tmp as $r) {
                        $user[$r['uid']] = $r;
                    }
                }
            }

            if($supplierids){
                $sql = "SELECT `id`,`supplier` FROM {$this->_prefix['primary']}supplier WHERE `id` IN (" . implode(",", $supplierids) . ")";
                $tmp = $this->sql($sql);
                if ($tmp) {
                    foreach ($tmp as $r) {
                        $supplier_data[$r['id']] = $r['supplier'];
                    }
                }

            }

            foreach ($data as $k => $r) {

                if ($r['warehouse_type']) {
                    $data[$k]['warehouse_name'] = $this->c['warehouse_types'][$r['warehouse_type']];

                }
                if ($user[$r['uid']]) {
                    //$data[$k]['username'] = $user[$r['uid']]['username'] . ' ' . $user[$r['uid']]['bank_realname'];
                    $data[$k]['name'] = $user[$r['uid']]['name'];
                    $data[$k]['recode'] = $user[$r['uid']]['recode'];

                }

                $data[$k]['supplier_name'] = $supplier_data[$r['supplierid']];

            }

            return $data;
        }
    }


    //获取未发货的订单信息
    public function getOrderAllDatas($para)
    {

        $where = "  ";

        if ($para['uid']) {
            $where .= " AND  ord.`uid`=" . $para['uid'];
        }

        if (isset($para['tui']) && $para['tui'] == "yes") {

            $where .= " AND ( ord.`pay_status` IN (3,4) OR  ord.`shipping_status` IN (7,8))";
        } else {

            if (isset($para['shipping_status']) && $para['shipping_status'] >= 0) {
                $where .= " AND  ord.`shipping_status`=" . $para['shipping_status'];
            }

            if (isset($para['pay_status']) && $para['pay_status'] >= 0) {
                $where .= " AND  ord.`pay_status`=" . $para['pay_status'];
            }
        }

        if ($para['province_id'] > 0) {
            $where .= " AND  ord.`province_id`=" . $para['province_id'];
        }

        if ($para['city_id'] > 0) {
            $where .= " AND  ord.`city_id`=" . $para['city_id'];
        }

        if ($para['county_id'] > 0) {
            $where .= " AND  ord.`county_id`=" . $para['county_id'];
        }
        // echo $where;die;
        if ($para['shipping_id'] > 0) {
            $where .= " AND  ord.`shipping_id`=" . $para['shipping_id'];
        }

        if ($para['keyword'] != '') {
            if (is_numeric($para['keyword'])) {
                $where .= " AND ( ord.`order_id`=" . $para['keyword'] . " OR  ord.`order_sn`='" . $para['keyword'] . "')";
            } else {
                $where .= " AND  ord.`consignee` LIKE '%" . $para['keyword'] . "%'";
            }

        }

        if ($para['gkwd'] != "") {
            if (is_numeric($para['gkwd'])) {
                $gsql = "`goods_id`=" . $para['gkwd'];
            } else {
                $gsql .= "`goods_name` LIKE '%" . $para['gkwd'] . "%'";
            }
            $sql = "SELECT `order_id` FROM {$this->_prefix['primary']}order_goods WHERE " . $gsql;
            $tmp = $this->sql($sql);
            if ($tmp) {
                foreach ($tmp as $r) {
                    $goids[] = $r['order_id'];
                }

                $where .= " AND  ord.`order_id` IN (" . implode(",", array_unique($goids)) . ")";
            } else {
                $where .= " AND  ord.`order_id`<0";
            }
        }

        if ($para['start_time']) {

            $where .= " AND ord.`add_time` >=" . $para['start_time'];

        }

        if ($para['end_time']) {

            $where .= " AND ord.`add_time` <=" . $para['end_time'];

        }

        if ($para['sell_type']) {

            $where .= " AND ord.`sell_type` =" . $para['sell_type'];

        }
        if ($para['recode']) {

            $sql  = "SELECT `uid`  FROM {$this->_prefix['primary']}member_account WHERE `recode` ='".$para['recode']."'";
            $uid = $this->db->getone($sql);

            $where .= " AND ord.`uid`=" .$uid;

        }

        $sql = "SELECT ord.*,ogd.* FROM {$this->_prefix['primary']}order_info ord INNER JOIN {$this->_prefix['primary']}order_goods ogd ON ogd.`order_id` = ord.`order_id` " . $where . " ORDER BY ogd.`rec_id` ASC,ogd.`order_id` ASC";

        $data = $this->sql($sql);

        if ($data) {
            foreach ($data as $r) {
                if ($r['uid'] > 0) {
                    $uids[$r['uid']] = $r['uid'];
                }
                if($r['supplierid']>0){

                    $supplierids[$r['supplierid']] = $r['supplierid'];
                }
            }

            if ($uids) {
                $sql = "SELECT `uid`,`realname`,`name`,`recode` FROM {$this->_prefix['primary']}member_account WHERE `uid` IN (" . implode(",", $uids) . ")";
                $tmp = $this->sql($sql);
                if ($tmp) {
                    foreach ($tmp as $r) {
                        $user[$r['uid']] = $r;

                    }
                }
            }

            if($supplierids){
                $sql = "SELECT `id`,`supplier` FROM {$this->_prefix['primary']}supplier WHERE `id` IN (" . implode(",", $supplierids) . ")";
                $tmp = $this->sql($sql);
                if ($tmp) {
                    foreach ($tmp as $r) {
                        $supplier_data[$r['id']] = $r['supplier'];
                    }
                }

            }

            foreach ($data as $k => $r) {

                if ($r['warehouse_type']) {
                    $data[$k]['warehouse_name'] = $this->c['warehouse_types'][$r['warehouse_type']];

                }
                if ($user[$r['uid']]) {
                   // $data[$k]['username'] = $user[$r['uid']]['username'] . ' ' . $user[$r['uid']]['bank_realname'];
                    $data[$k]['name'] = $user[$r['uid']]['name'];
                    $data[$k]['recode'] = $user[$r['uid']]['recode'];
                }

                $data[$k]['supplier_name'] = $supplier_data[$r['supplierid']];

            }

            return $data;
        }
    }

    // 保存订单快递信息
    public function saveImport($da)
    {
        $code = 404;

        if (is_array($da)) {

            $this->db->begin();
            $commit = false;
            $code   = 403;
            foreach ($da as $r) {
                $rec_id = intval($r[0]);
                if ($rec_id > 0 && $r[1] != "") {

                    $shipping_id    = addslashes(htmlspecialchars(trim($r[5])));
                    $shipping_name  = addslashes(htmlspecialchars(trim($r[6])));
                    $order_sn       = addslashes(htmlspecialchars(trim($r[1])));
                    $purchase_price = addslashes(htmlspecialchars(trim($r[15])));

                    if ($shipping_id != "" && $shipping_name != "") {
                        $shipping_status = ",`shipping_status`=1";
                        $time            = $_SERVER['REQUEST_TIME'];
                    } else {
                        $shipping_status = ",`shipping_status`=0";
                        $time            = 0;

                    }

                    $sql              = "SELECT `order_id`,`goods_id` FROM {$this->_prefix['primary']}order_goods WHERE `rec_id`=" . $rec_id;
                    $order_goods_info = $this->db->getrow($sql);

                    $sql = "UPDATE {$this->_prefix['primary']}order_goods SET `shipping_id`='" . $shipping_id . "',`shipping_name`='" . $shipping_name . "',`purchase_price`='" . $purchase_price . "',`shipping_time`=" . $time . $shipping_status . "  WHERE `rec_id`=" . $rec_id;
                    $rcs = $this->sql($sql);

                    if ($rcs > 0) {

                        $sql = "SELECT COUNT(`rec_id`) AS `cnt` FROM {$this->_prefix['primary']}order_goods WHERE order_id=" . $order_goods_info['order_id'] . " AND shipping_status = 0";
                        $cnt = $this->db->getone($sql);
                        if ($cnt > 0) {

                            $shipping_status = 3;

                        } else {

                            $shipping_status = 1;
                        }
                        $sql  = "SELECT `order_id`,`shipping_status` FROM {$this->_prefix['primary']}order_info WHERE `order_id`=" . $order_goods_info['order_id'];
                        $info = $this->db->getrow($sql);

                        if ($info['shipping_status'] != $shipping_status) {
                            $sql   = "UPDATE {$this->_prefix['primary']}order_info SET `shipping_status`=" . $shipping_status . " WHERE `order_id`=" . $order_goods_info['order_id'];
                            $re_id = $this->sql($sql);

                            if ($re_id) {

                                $commit = true;

                            }

                        } else {

                            $commit = true;
                        }
                    }
                }

            }

            if ($commit) {
                $this->db->commit();
                $code = 200;
            } else {
                $this->db->rollback();
            }
        }

        return $code;
    }

    //修改订单地址信息
    public function updateRegion($data)
    {
        $province_id = intval($data['parent_id']);
        $city_id     = intval($data['city_id']);
        $county_id   = intval($data['county_id']);
        $address     = htmlspecialchars(trim($data['i_address']));
        $consignee   = htmlspecialchars(trim($data['consignee']));
        $mobile      = intval($data['mobile']);
        $idnum       = $data['idnum'];
        $sql         = "UPDATE {$this->_prefix['primary']}order_info SET `province_id`=$province_id,`city_id`=$city_id,`county_id`=$county_id,`address`='" . $address . "',`consignee`='" . $consignee . "',`mobile`='" . $mobile . "',`idnum`='" . $idnum . "' WHERE order_id = " . $data['order_id'];
        $data        = $this->sql($sql);
        if ($data) {
            $code = 200;
        } else {
            $code = 403;
        }
        return array('code' => $code);

    }

    // AJAX获取区域信息
    public function getRegionAjax($parent_id = 0)
    {
        $sql = "SELECT `region_id`,`region_name` FROM {$this->_prefix['primary']}region WHERE `parent_id`=" . intval($parent_id);

        $data = $this->sql($sql);
        if ($data) {
            foreach ($data as $r) {
                $new[$r['region_id']] = $r['region_name'];
            }
            return $new;
        } else {
            return false;
        }

    }

    // 获取区域信息
    public function getRegion()
    {
        $sql  = "SELECT `region_id`,`region_name` FROM {$this->_prefix['primary']}region ORDER BY `region_id` ASC";
        $data = $this->sql($sql);
        if ($data) {
            foreach ($data as $r) {
                $new[$r['region_id']] = $r['region_name'];
            }

            return $new;
        }
    }

    //订单列表
    public function getOrder($para, $page = 1, $pagesize = 20)
    {

        $where = " 1=1 ";

        if ($para['uid']) {
            $where .= " AND `uid`=" . $para['uid'];
        }

        if (isset($para['tui']) && $para['tui'] == "yes") {

            $where .= " AND (`pay_status` IN (3,4) OR `shipping_status` IN (7,8))";
        } else {

            if (isset($para['shipping_status']) && $para['shipping_status'] >= 0) {
                $where .= " AND `shipping_status`=" . $para['shipping_status'];
            }

            if (isset($para['pay_status']) && $para['pay_status'] >= 0) {
                $where .= " AND `pay_status`=" . $para['pay_status'];
            }
        }

        if ($para['province_id'] > 0) {
            $where .= " AND `province_id`=" . $para['province_id'];
        }

        if ($para['city_id'] > 0) {
            $where .= " AND `city_id`=" . $para['city_id'];
        }

        if ($para['county_id'] > 0) {
            $where .= " AND `county_id`=" . $para['county_id'];
        }
 // echo $where;die;
        if ($para['shipping_id'] > 0) {
            $where .= " AND `shipping_id`=" . $para['shipping_id'];
        }

        if ($para['keyword'] != '') {
            if (is_numeric($para['keyword'])) {
                $where .= " AND (`order_id`=" . $para['keyword'] . " OR `order_sn`='" . $para['keyword'] . "')";
            } else {
                $where .= " AND `consignee` LIKE '%" . $para['keyword'] . "%'";
            }

        }


        if ($para['gkwd'] != "") {
            if (is_numeric($para['gkwd'])) {
                $gsql = "`goods_id`=" . $para['gkwd'];
            } else {
                $gsql .= "`goods_name` LIKE '%" . $para['gkwd'] . "%'";
            }
            $sql = "SELECT `order_id` FROM {$this->_prefix['primary']}order_goods WHERE " . $gsql;
            $tmp = $this->sql($sql);
            if ($tmp) {
                foreach ($tmp as $r) {
                    $goids[] = $r['order_id'];
                }

                $where .= " AND `order_id` IN (" . implode(",", array_unique($goids)) . ")";
            } else {
                $where .= " AND `order_id`<0";
            }
        }

        if ($para['start_time']) {

            $where .= " AND `add_time` >=" . $para['start_time'];
            $para['start_time'] = date("Y-m-d H:i", $para['start_time']);
        }

        if ($para['end_time']) {

            $where .= " AND `add_time` <=" . $para['end_time'];
            $para['end_time'] = date("Y-m-d H:i", $para['end_time']);
        }

        if ($para['sell_type']) {

            $where .= " AND `sell_type` =" . $para['sell_type'];

        }

        if ($para['recode']) {

            $sql  = "SELECT `uid`  FROM {$this->_prefix['primary']}member_account WHERE `recode` ='".$para['recode']."'";
            $uid = $this->db->getone($sql);

            $where .= " AND `uid`=" .$uid;

        }

        $sql = "SELECT COUNT(`order_id`) AS `cnt` FROM {$this->_prefix['primary']}order_info WHERE " . $where;
        $cnt = $this->sql($sql);
        if ($cnt[0]['cnt'] > 0) {

            $start = ($page - 1) * $pagesize;
            //默认排序
            $orderby = "`add_time` DESC,`order_id` DESC";
            //查询订单信息
            $sql = "SELECT `order_id`,`order_sn`,`uid`,`order_status`,`province_id`,`city_id`,`county_id`,`address`,`shipping_status`,`mobile`,`pay_status`,`order_amount`,`shipping_name`,`pay_fee`,`add_time`,`consignee`,`store_stat`,`shipping_id`,`print_stat`,`sell_type`,`pick_up_status`,`pick_up_time`,`gold_fee`,`coupon_fee`,`discount_fee` FROM {$this->_prefix['primary']}order_info WHERE " . $where . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;
            $rs  = $this->sql($sql);

            if ($rs) {
                foreach ($rs as $k => $v) {

                    // 区域信息
                    if ($v['province_id'] > 0) {
                        $region_id[] = $v['province_id'];
                    }

                    if ($v['city_id'] > 0) {
                        $region_id[] = $v['city_id'];
                    }

                    if ($v['county_id'] > 0) {
                        $region_id[] = $v['county_id'];
                    }

                }

                if ($region_id) {
                    $sql         = "SELECT `region_id`,`region_name` FROM {$this->_prefix['primary']}region WHERE `region_id` IN (" . implode(",", $region_id) . ")";
                    $region_data = $this->sql($sql);
                    if ($region_data) {
                        foreach ($region_data as $r) {
                            $region[$r['region_id']] = $r['region_name'];
                        }
                    }
                }
            }
        }
        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt[0]['cnt'] / $pagesize),
            'count'   => $cnt[0]['cnt'],
            'data'    => $rs,
            'para'    => $para,
            'region'  => $region,
        );
    }

    public function getOrderMoneyCount($para)
    {
        $where = " 1=1 ";

        if ($para['uid']) {
            $where .= " AND `uid`=" . $para['uid'];
        }

        if (isset($para['tui']) && $para['tui'] == "yes") {

            $where .= " AND (`pay_status` IN (3,4) OR `shipping_status` IN (7,8))";
        } else {

            if (isset($para['shipping_status']) && $para['shipping_status'] >= 0) {
                $where .= " AND `shipping_status`=" . $para['shipping_status'];
            }

            if (isset($para['pay_status']) && $para['pay_status'] >= 0) {
                $where .= " AND `pay_status`=" . $para['pay_status'];
            }
        }

        if ($para['province_id'] > 0) {
            $where .= " AND `province_id`=" . $para['province_id'];
        }

        if ($para['city_id'] > 0) {
            $where .= " AND `city_id`=" . $para['city_id'];
        }

        if ($para['county_id'] > 0) {
            $where .= " AND `county_id`=" . $para['county_id'];
        }
        // echo $where;die;
        if ($para['shipping_id'] > 0) {
            $where .= " AND `shipping_id`=" . $para['shipping_id'];
        }

        if ($para['keyword'] != '') {
            if (is_numeric($para['keyword'])) {
                $where .= " AND (`order_id`=" . $para['keyword'] . " OR `order_sn`='" . $para['keyword'] . "')";
            } else {
                $where .= " AND `consignee` LIKE '%" . $para['keyword'] . "%'";
            }

        }

        if ($para['gkwd'] != "") {
            if (is_numeric($para['gkwd'])) {
                $gsql = "`goods_id`=" . $para['gkwd'];
            } else {
                $gsql .= "`goods_name` LIKE '%" . $para['gkwd'] . "%'";
            }
            $sql = "SELECT `order_id` FROM {$this->_prefix['primary']}order_goods WHERE " . $gsql;
            $tmp = $this->sql($sql);
            if ($tmp) {
                foreach ($tmp as $r) {
                    $goids[] = $r['order_id'];
                }

                $where .= " AND `order_id` IN (" . implode(",", array_unique($goids)) . ")";
            } else {
                $where .= " AND `order_id`<0";
            }
        }

        if ($para['start_time']) {

            $where .= " AND `add_time` >=" . $para['start_time'];
            $para['start_time'] = date("Y-m-d H:i", $para['start_time']);
        }

        if ($para['end_time']) {

            $where .= " AND `add_time` <=" . $para['end_time'];
            $para['end_time'] = date("Y-m-d H:i", $para['end_time']);
        }

        if ($para['sell_type']) {

            $where .= " AND `sell_type` =" . $para['sell_type'];

        }
        if ($para['recode']) {

            $sql  = "SELECT `uid`  FROM {$this->_prefix['primary']}member_account WHERE `recode` ='".$para['recode']."'";
            $uid = $this->db->getone($sql);

            $where .= " AND `uid`=" .$uid;

        }

        //查询订单信息
        $sql = "SELECT `order_id`,`order_amount` FROM {$this->_prefix['primary']}order_info WHERE " . $where ;
        $rs  = $this->sql($sql);

        $total_money = 0;
        if($rs){
            foreach($rs as $v){
                $total_money +=$v['order_amount'];

            }

        }

        return $total_money;

    }

    //获取用户昵称

    public function getMemberInfo($uid)
    {
        if ($uid) {
            $sql  = "SELECT `uid`,`realname`,`headimgurl`,`member_level`,`name`,`recode` FROM {$this->_prefix['primary']}member_account WHERE `uid` IN (" . implode(",", array_unique($uid)) . ")";
            $data = $this->sql($sql);

            if ($data) {
                foreach ($data as $r) {
                    $user[$r['uid']] = $r;
                    if ($r['headimgurl'] > 0) {
                        $docid[] = $r['headimgurl'];
                    }

                }
                if ($docid) {
                    $docs = $this->getDocs($docid);
                }

                return $user;
            } else {
                return false;
            }

        }
    }

    //获取物流信息
    public function getCourier($shipping_id, $shipping_name)
    {

        if ($shipping_id != "" && $shipping_name != "") {

            $redis_key = 'LEATIEN_EXPRESS_' . $shipping_id . md5($shipping_name);

            $timestamp = $_SERVER['REQUEST_TIME'];
            $st        = md5($this->appid . $shipping_id . $shipping_name . $timestamp . $this->appkey);
            $url       = "http://api.leatien.com/express/get?appid=" . $this->appid . "&shipping_name=" . $shipping_name . "&shipping_id=" . $shipping_id . "&timestamp=" . $timestamp . "&st=" . $st;

            $tmpdata = file_get_contents($url);
            if ($tmpdata != "") {
                $tmpdata = json_decode($tmpdata, true);
                if ($tmpdata['code'] == 200) {

                    $tmpdata['content']    = unserialize($tmpdata['content']);
                    $data['shipping_id']   = $shipping_id;
                    $data['shipping_name'] = $shipping_name;
                    $data['info']          = $tmpdata['content']['data']['origin_info']['trackinfo'];

                    $this->redis->setex($redis_key, 1200, json_encode($data));

                    return $data;
                }
            }

        }

    }

    //修改进货价
    public function savePurchasePrice($da)
    {

        $code           = 900;
        $msg            = "修改失败";
        $rec_id         = intval($da['rec_id']);
        $purchase_price = intval($da['purchase_price']);

        $arr = array();
        if ($rec_id && $purchase_price) {

            $sql = "UPDATE {$this->_prefix['primary']}order_goods SET `purchase_price`=" . $purchase_price . " WHERE `rec_id`=" . $rec_id;
            $res = $this->sql($sql);
            if ($res) {
                $code = 200;
                $msg  = "修改成功";
            }
        } else {
            $code = 901;
        }
        $arr['code'] = $code;
        $arr['msg']  = $msg;
        return $arr;
    }
    //修改供应商
    public function saveSupplierid($da)
    {
        $code       = 900;
        $msg        = "修改失败";
        $rec_id     = intval($da['rec_id']);
        $supplierid = intval($da['supplierid']);
        $this->db->begin();
        $commit = false;
        $arr    = array();

        if ($rec_id && $supplierid) {
            $sql              = "SELECT `order_id`,`supplierid`,`goods_id` FROM {$this->_prefix['primary']}order_goods WHERE `rec_id`=" . $rec_id;
            $order_goods_info = $this->db->getrow($sql);

            if (!empty($order_goods_info)) {

                if ($order_goods_info['supplierid'] != $supplierid) {
                    $sql = "UPDATE {$this->_prefix['primary']}order_goods SET `supplierid`=" . $supplierid . " WHERE `rec_id`=" . $rec_id;
                    $res = $this->sql($sql);

                    if ($res) {

                        $sql = "UPDATE {$this->_prefix['primary']}goods_data SET `supplierid`=" . $supplierid . " WHERE `goods_id`=" . $order_goods_info['goods_id'];
                        $rs  = $this->sql($sql);
                        if ($rs > 0) {
                            $commit = true;
                            $code   = 200;
                            $msg    = "修改成功";

                        }

                    }

                } else {
                    $msg  = "供应商未改变";
                    $code = 903;

                }
            } else {
                $code = 902;

            }

        } else {
            $code = 901;
        }

        if ($commit) {
            $this->db->commit();
            $code = 200;
        } else {
            $this->db->rollback();
        }

        $arr['code'] = $code;
        $arr['msg']  = $msg;
        return $arr;
    }

    //  确认收货
    public function saveSeceiveOrder($data)
    {
        $code = 900;
        $msg  = "确认收货失败！";
        //开始事务
        $this->db->begin();
        $rollback = true;
        if ($data['rec_id']) {
            $rec_id = intval($data['rec_id']);
        }
        if ($data['order_id']) {
            $order_id = intval($data['order_id']);
        }

        if ($rec_id > 0 && $order_id > 0) {

            $sql  = "UPDATE {$this->_prefix['primary']}order_goods SET `shipping_status`=2  WHERE `rec_id`=" . $rec_id;
            $rows = $this->sql($sql);

            if ($rows) {
                $sql = "SELECT COUNT(`rec_id`) AS `cnt` FROM {$this->_prefix['primary']}order_goods WHERE `order_id`=" . $order_id . " AND (`refund_status` NOT IN (0,5,3) OR `return_goods_status` NOT IN (0,5,7) OR `shipping_status` NOT IN (2,9))";
                $cnt = $this->db->getone($sql);

                if ($cnt > 0) {
                    $msg  = "确认收货成功！";
                    $code = 200;
                    $this->db->commit();
                    $rollback = false;
                } else {
                    $sql = "UPDATE {$this->_prefix['primary']}order_info SET `shipping_status`=2,`order_status`=7  WHERE `order_id`=" . $order_id;
                    //echo $sql;die;
                    $rod = $this->sql($sql);
                    if ($rod) {

                        $msg  = "确认收货成功！";
                        $code = 200;
                        $this->db->commit();
                        $rollback = false;
                    } else {

                        $code = 903;
                    }
                }

            } else {

                $code = 902;
            }
        } else {
            $msg  = "ID不能为空，请重试！";
            $code = 901;

        }

        if ($rollback) {
            $this->db->rollback();
        }

        $data['code'] = $code;
        $data['msg']  = $msg;
        return $data;

    }

    //获取一元购相关记录
    public function getOrderBidRecord($orderid)
    {
        $orderid = intval($orderid);
        $where   = "`order_id`=" . $orderid;
        //获取加价记录数据
        $bidsql    = "SELECT `order_id`,ob.`uid`,`bid_price`,ob.`create_time`,ma.`mobile`,`member_level` FROM {$this->_prefix['primary']}order_bidrecord ob LEFT JOIN {$this->_prefix['primary']}member_account ma ON ma.`uid`= ob.`uid`  WHERE " . $where . " ORDER BY `create_time`";
        $bidresult = $this->sql($bidsql);

        //获取补偿记录数据
        $rebidsql    = "SELECT `order_id`,ob.`uid`,`bid_price`,`equalize_price`,ob.`create_time`,ma.`mobile`,`member_level`,ob.`rebid_type`  FROM {$this->_prefix['primary']}order_bidrecord ob LEFT JOIN {$this->_prefix['primary']}member_account ma ON ma.`uid`= ob.`uid` WHERE " . $where . " ORDER BY `create_time`";
        $rebidresult = $this->sql($rebidsql);

        //冻结云米记录数据
        $freezesql    = "SELECT `order_id`,ob.`uid`,`freeze_price`,`freeze_status`,`freeze_time`,ma.`mobile`,`member_level` FROM {$this->_prefix['primary']}order_bidfreeze ob LEFT JOIN {$this->_prefix['primary']}member_account ma ON ma.`uid`= ob.`uid` WHERE " . $where . " ORDER BY ob.`create_time`";
        $freezeresult = $this->sql($freezesql);

        $data['biddata']    = $bidresult;
        $data['rebiddata']  = $rebidresult;
        $data['freezedata'] = $freezeresult;

        return $data;
    }

}
